0414. 第三大的数【简单】
1. 📝 题目描述
给你一个非空数组,返回此数组中 第三大的数。如果不存在,则返回数组中最大的数。
示例 1:
txt
输入:[3, 2, 1]
输出:1
解释:第三大的数是 1。1
2
3
2
3
示例 2:
txt
输入:[1, 2]
输出:2
解释:第三大的数不存在, 所以返回最大的数 2。1
2
3
2
3
示例 3:
txt
输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1。1
2
3
4
2
3
4
提示:
1 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1
进阶:
- 你能设计一个时间复杂度
O(n)的解决方案吗?
2. 🎯 s.1 - 一次遍历维护三个变量
js
/**
* @param {number[]} nums
* @return {number}
*/
var thirdMax = function (nums) {
// 使用三个变量分别记录最大、第二大、第三大的数
// 初始化为负无穷,表示还没有赋值
let first = -Infinity // 最大
let second = -Infinity // 第二大
let third = -Infinity // 第三大
for (const num of nums) {
// 如果当前数字已经存在于前三大的数中,跳过
if (num === first || num === second || num === third) {
continue
}
// 更新前三大的数
if (num > first) {
// 当前数字比最大值还大,更新 third、second、first
third = second
second = first
first = num
} else if (num > second) {
// 当前数字比第二大值大,但比最大值小,更新 third、second
third = second
second = num
} else if (num > third) {
// 当前数字比第三大值大,更新 third
third = num
}
}
// 如果第三大值仍然是初始值,说明不存在第三大的数,返回最大值
return third === -Infinity ? first : third
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
3. 🎯 s.2 - 使用 Set 去重 + 排序
js
/**
* @param {number[]} nums
* @return {number}
*/
var thirdMax = function (nums) {
const uniqueNums = [...new Set(nums)]
uniqueNums.sort((a, b) => b - a)
return uniqueNums.length >= 3 ? uniqueNums[2] : uniqueNums[0]
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
4. 🎯 s.3 - 使用数组维护前三大的数
js
/**
* @param {number[]} nums
* @return {number}
*/
var thirdMax = function (nums) {
const topThree = []
for (const num of nums) {
if (topThree.includes(num)) {
continue
}
topThree.push(num)
topThree.sort((a, b) => b - a)
// 保持数组长度为3
if (topThree.length > 3) {
topThree.pop()
}
}
// 如果有 3 个数,返回最小的(第三大);否则返回最大的
return topThree.length === 3 ? topThree[2] : topThree[0]
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24